package com.unione.unione_network.tcp_socket.bean

import java.util.Arrays
import java.util.concurrent.atomic.AtomicInteger

enum class MsgType {
    Send,
    Receive
}

data class TcpMsg(
    var id: Int = generateId(),
    var sourceDataBytes: ByteArray? = null,
    var sourceDataString: String? = null,
    var target: TargetInfo?=null,
    var time: Long = currentTimeMillis(),
    var msgType: MsgType = MsgType.Send,
    var endDecodeData: Array<ByteArray>? = null
) {

    companion object {
        private val idGenerator = AtomicInteger()

        fun generateId(): Int = idGenerator.incrementAndGet()

        fun currentTimeMillis(): Long = System.currentTimeMillis()
    }

    fun setTime(): Unit {
        time = currentTimeMillis()
    }

    fun getEndDecodeDataAsString(): String =
        endDecodeData?.joinToString(separator = "") { it.contentToString() } ?: ""

    override fun toString(): String {
        val sb = StringBuilder()
        endDecodeData?.forEach { sb.append(it.contentToString()) }
        return "TcpMsg{" +
                "sourceDataBytes=" + Arrays.toString(sourceDataBytes) +
                ", id=$id" +
                ", sourceDataString='$sourceDataString'" +
                ", target=$target" +
                ", time=$time" +
                ", msgType=$msgType" +
                ", endDecodeData=${sb.toString()}" +
                '}'
    }
}